package com.yugao.fintech.antelope.system.handler.config;

import com.alibaba.fastjson2.JSON;
import com.yugao.fintech.antelope.base.config.GlobalProperties;
import com.yugao.fintech.antelope.infra.InfraApi;
import com.yugao.fintech.antelope.infra.common.InfraCons;
import com.yugao.fintech.antelope.infra.common.QrCodeSceneEnum;
import com.yugao.fintech.antelope.infra.common.ScanScene;
import com.yugao.fintech.antelope.base.model.constants.ServiceCodeCons;
import com.yugao.fintech.antelope.base.model.enums.ConfigKeyEnum;
import com.yugao.fintech.antelope.base.model.module.config.param.BaseConfigParam;
import com.yugao.fintech.antelope.base.model.module.config.param.WxMpParam;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.antelope.system.model.entity.SysConfig;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.assistant.utils.UrlUtils;
import org.springframework.stereotype.Component;

import java.util.Optional;


@Component
public class WxMpConfigHandler extends ConfigHandler {
    @Autowired
    private InfraApi infraApi;
    @Autowired
    private GlobalProperties properties;

    @Override
    public void doneWriteOps(SysConfig newConfig, BaseConfigParam<?> param) {
        WxMpParam wxMpParam = (WxMpParam) param;

        if (StringUtils.isEmpty(wxMpParam.getQrCodeUrl())) {
            // 获取微信公众号二维码, 扫码获取openId
            // 当用户扫码之后, 会在 infra 服务中收到微信服务器的推送扫码事件, 然后由infra服务将数据推送到push服务最终通过websocket返回给前端
            ScanScene scanScene = ScanScene.builder().isRefresh(true).sceneCode(QrCodeSceneEnum.DEFAULT.getCode()).build();
            String qrcode = infraApi.getMpQrcode(scanScene);
            wxMpParam.setQrCodeUrl(qrcode);
        }
        newConfig.setConfigValue(JSON.toJSONString(wxMpParam));
    }

    @Override
    protected BaseConfigParam<?> doneReadOps(BaseConfigParam<?> param) {
        WxMpParam wxMpParam = (WxMpParam) param;
        wxMpParam = Optional.ofNullable(wxMpParam).orElse(new WxMpParam());
        Long tenantId = TenantContextHolder.get().getTenantId();

        String url = UrlUtils.removeRepeatSlashOfUrl(
                properties.getServerAddr() + "/" + ServiceCodeCons.INFRA_SERVICE + InfraCons.URL_WX_MP_PUSH + "/" + tenantId
        );
        wxMpParam.setMsgPushUrl(url);
        return wxMpParam;
    }

    @Override
    public ConfigKeyEnum configKey() {
        return ConfigKeyEnum.WX_MP;
    }
}
